package com.xiaodou.mjf.web.xface.user.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.core.service.LoanService;
import com.xiaodou.mjf.application.fee.service.AccountFeeService;
import com.xiaodou.mjf.application.fee.service.LoanMasterService;
import com.xiaodou.mjf.application.fee.service.RepaymentPlanDetailService;
import com.xiaodou.mjf.entity.core.Loan;
import com.xiaodou.mjf.entity.fee.AccountFee;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.web.xface.common.ResultCode;
import com.xiaodou.mjf.web.xface.product.domain.BillProductDetail;

@RestController
@RequestMapping("v1/user")
public class BillController extends ApiController {
	@Resource
	LoanService loanService;

	@Resource
	LoanMasterService loanMasterService;

	@Resource
	AccountFeeService accountFeeService;

	@Resource
	RepaymentPlanDetailService repaymentPlanDetailService;

	public static final String PAY_OFF = "02";

	public static final String UNPAID = "01";
	// 账单日
	public static final String STATEMENT_DATE = "每月月底";
	// 到期还款日
	public static final String REPAYMENT_DATE = "每月10日";

	@RequestMapping("my/bills")
	Map<String, Object> detailInquiry(
			@RequestHeader(required = false) String uid, Integer start,
			Integer row) {
		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}
		Map<String, Object> result = success();
		// BillDetail billDetail = new BillDetail();
		// List<BillProductDetail> billProductDetails = new
		// ArrayList<BillProductDetail>();
		// if(start == null || start < 0){
		// start = 0;
		// }
		//
		// if(row == null){
		// row = 20;
		// }
		// Loan entity = new Loan ();
		// entity.setMemberId(uid);
		// entity.setStart(start);
		// entity.setLimit(row);
		// //当月最后一天时间
		// // Calendar cDay = Calendar.getInstance();
		// // cDay.setTime(DateUtils.getCurrentTime());
		// // int lastDay = cDay.getActualMaximum(Calendar.DAY_OF_MONTH);
		//
		// entity.setCreateTime(DateUtils.getCurrentTime());
		// entity.setStatus(Financing.NORMAL);
		// Page<Loan> page = loanService.pageByDate(entity);
		// List<Loan> loans = page.getContent();
		// //已还期数为
		// // for(Loan loan:loans){
		// // billProductDetails.add(new BillProductDetail(loan.getProductId(),
		// // loan.getProjectName(),
		// loan.getLoanAmount(),loan.getCreateTime(),loan.getTerm(),new
		// Integer(1)));
		// // }
		// //账单清算标识
		// result.put("is_cleared", billDetail.getIsCleared());
		// //账单金额
		// result.put("bill_amount", billDetail.getBillAmount());
		// //已还金额
		// result.put("repaid_amount", billDetail.getRepaidAmount());
		// //账单日
		// result.put("statement_date", "每月月底");
		// //到期还款日
		// result.put("repayment_date", "每月10日");
		//
		// result.put("items", billProductDetails);

		return result;
	}

	@RequestMapping("my/bills/{year}-{month}")
	Map<String, Object> detailList(@PathVariable String year,
			@PathVariable String month,
			@RequestHeader(required = false) String uid) {

		if (StringUtils.isBlank(uid)) {
			return failure(ResultCode.MISSING_UID_PARAM);
		}
		Map<String, Object> result = success();
		//1,loan表查询 即账单表查询
		List<Loan> loans = loanService.findByDate(year, month, uid);
		//2,算出未还金额 需要关联loan表 和loan_master表
		List<AccountFee> accountFees = accountFeeService.findByMemberIdAndYearAndMonth(uid, Integer.parseInt(year),Integer.parseInt(month));
		if (accountFees.size() == 0 || loans.size() == 0) {
			return failure(ResultCode.BILL_NOT_EXIST);
		}
		// 账单金额
		// double sumTotalRepaymentAmount =0D;
		// 未还金额
		double arrearsAmount = 0D;
		for (AccountFee accountFee : accountFees) {
			// //账单金额
			// sumTotalRepaymentAmount+=RepaymentAmount==null?0:RepaymentAmount;
			// 未还金额
			arrearsAmount += accountFee.getArrearsAmount() == null ? 0: accountFee.getArrearsAmount().doubleValue();
		}

		List<BillProductDetail> billProductDetails = new ArrayList<BillProductDetail>();
		// uid->account_fee表的member_id->account_fee表的account_number->loan_master->loan_id->loan表
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 账单清算标识 用account_fee表的 未还金额 sum值来判断，如果不为0则 返回“01”表示未还清账单 如果为0 则返回02还清。
		// Double sumArrearsAmount
		// =accountFeeService.sumArrearsAmount(uid,Integer.parseInt(year),Integer.parseInt(month));
		if (arrearsAmount == 0D) {
			result.put("is_cleared", PAY_OFF);
		} else {
			result.put("is_cleared", UNPAID);
		}
		for (Loan loan : loans) {
			// 已还期数计算： 取出account_fee表的account_number字段
			// 然后依据状态repayment_status来算出accout_number 的记录数
			int term = accountFeeService.sumTerm((loanMasterService.findByLoanId(loan.getId())).getAccountNumber(), 0,loan.getMemberId());
			billProductDetails.add(new BillProductDetail(loan.getProductId(),loan.getProjectName(), loan.getProjectAmount(), sdf.format(loan.getCreateTime()).toString(), loan.getTerm(),term));
		}
		// 已还金额 暂不支持分期还款
		result.put("repaid_amount", 0);
		// 账单金额
		result.put("bill_amount", arrearsAmount);
		// 账单日
		result.put("statement_date", STATEMENT_DATE);
		// 到期还款日
		result.put("repayment_date", REPAYMENT_DATE);
		// 账单详情
		result.put("items", billProductDetails);

		return result;
	}

}
